package com.kehutong.crm.message.service;

import java.sql.Timestamp;
import java.util.List;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.condition.ConditionLike.LikeType;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.orm.util.Enums;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;
import com.kehutong.common.DoveClient;
import com.kehutong.common.dto.UniformSendReqDto;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.MessageBusinessStateEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.crm.message.entity.Message;
import com.kehutong.crm.message.entity.MessageAccount;
import com.kehutong.crm.message.entity.MessageAccountConfig;
import com.kehutong.crm.message.entity.MessageClassify;
import com.kehutong.crm.message.entity.MessageCorp;
import com.kehutong.crm.message.entity.MessageGlobalConfig;
import com.kehutong.crm.message.entity.MessageNotifyEmployee;
import com.kehutong.crm.message.entity.MessageTemplateInner;
import com.kehutong.crm.message.entity.MessageTemplateSms;
import com.kehutong.crm.message.entity.MessageUser;
import com.kehutong.crm.message.entity.UserExpand;
import com.kehutong.crm.message.enums.MessageReceiverType;
import com.kehutong.crm.message.enums.MessageType;

@WebService("/crm/message/service")
public class MessageService {
    static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private MessageAccountConfigService configService;
    @Inject
    private MessageGlobalConfigService globalConfigService;
    @Inject
    private MessageInnerService innerService;
    @Inject
    private DoveClient doveClient;
    @Inject
    private TencentSmsService tencentSmsService;

    public Object list(JSONObject jsonObject) {
        FindPage<Message> findPage = jdbcSession.findPage(Message.class)
                                                .eq(jsonObject, "classifyId", "releaseStatus", "releaseUserName")
                                                .like(jsonObject, "title")
                                                .eq("deleted", false);

        String createTime = jsonObject.getString("createTime");
        if (Objects.nonEmpty(createTime)) {
            findPage.like("createTime", createTime, LikeType.RIGHT);
        }

        findPage.order("createTime", "desc")
                .page(jsonObject);

        return Result.success(findPage.exe());
    }

    public Object save(Message message) {
        setClassifyName(message);
        jdbcSession.insert(message);

        return Result.success();
    }


    public Object update(Message message) {
        setClassifyName(message);
        jdbcSession.updateById(message);

        return Result.success();
    }

    private void setClassifyName(Message message) {
        MessageClassify classify = Pool.get(MessageClassify.class, message.getClassifyId());
        if (Objects.nonNull(classify)) {
            message.setClassifyName(classify.getName());

            Message oldCommon = Pool.get(Message.class, message.getId());
            if (Objects.isNull(oldCommon)){
                int count = classify.getCount() + 1;
                classify.setCount(count);
                jdbcSession.updateById(classify);
            } else if (!message.getClassifyId().equals(oldCommon.getClassifyId())){
                int count = classify.getCount() + 1;
                classify.setCount(count);
                jdbcSession.updateById(classify);

                MessageClassify oldClassify = Pool.get(MessageClassify.class, oldCommon.getClassifyId());
                if (Objects.nonNull(oldClassify)) {
                    int oldCount = oldClassify.getCount() - 1;
                    oldClassify.setCount(oldCount);
                    jdbcSession.updateById(oldClassify);
                }
            } else {
                // continue
            }
        }
    }

    public Object delete(Message message) {
        if (Objects.isNull(message)) {
            return Result.error(0, "消息不存在！");
        }

        message.setDeleted(true);
        jdbcSession.updateById(message);

        MessageClassify classify = Pool.get(MessageClassify.class, message.getClassifyId());
        int count = classify.getCount() - 1;
        classify.setCount(count);
        jdbcSession.updateById(classify);

        List<MessageUser> messageUserList = jdbcSession.findArray(MessageUser.class)
                                                       .eq("msgId", message.getId())
                                                       .exe();
        messageUserList.forEach(e -> {
            e.setDeleted(true);
            jdbcSession.updateById(e);
        });

        return Result.success();
    }

    public void businessRead(String id){
        MessageAccount account = Pool.get(MessageAccount.class, id);
        if (Objects.nonNull(account)){
            checkMsgRead(account);
        }
    }

    public void businessReadAll(String uuid){
        List<MessageAccount> accountList = jdbcSession.findArray(MessageAccount.class)
                                                      .eq("uuid", uuid)
                                                      .eq("read", false)
                                                      .eq("deleted", false)
                                                      .exe();
        accountList.forEach(this::checkMsgRead);

    }

    public void checkMsgRead(MessageAccount account) {
        if (!account.isRead()) {
            synchronized (account.getMsgId().intern()) {
                account.setRead(true);
                jdbcSession.updateById(account);

                if (MessageBusinessEnum.MSG_SYS_PLACARD == account.getBusinessEnum()) {
                    if (Objects.isEmpty(account.getCompanyNum())) {
                        Message message = Pool.get(Message.class, account.getMsgId());
                        if (message != null) {
                            // 阅读数+1
                            int readNum = message.getReadNum() + 1;
                            message.setReadNum(readNum);
                            jdbcSession.updateById(message);
                        }
                    } else {
                        MessageCorp message = Pool.get(MessageCorp.class, account.getMsgId());
                        if (message != null) {
                            // 阅读数+1
                            int readNum = message.getReadNum() + 1;
                            message.setReadNum(readNum);
                            jdbcSession.updateById(message);
                        }
                    }
                }
            }
        }
    }

    public Object remindList(JSONObject jsonObject, String uuid, String companyNo, Timestamp createTime, boolean userCreate) {
        checkUserLatest(uuid, companyNo, createTime, userCreate);

        return jdbcSession.findPage(MessageAccount.class)
                          .eq("uuid", uuid)
                          .noEq("businessEnum", MessageBusinessEnum.MSG_SYS_PLACARD)
                          .eq("deleted", false)
                          .order("read", "asc")
                          .order("createTime", "desc")
                          .page(jsonObject)
                          .exe();
    }

    public Object bulletinList(JSONObject jsonObject, String uuid, String companyNo, Timestamp createTime, boolean userCreate) {
        checkUserLatest(uuid, companyNo, createTime, userCreate);

        return jdbcSession.findPage(MessageAccount.class)
                          .eq(jsonObject, "successStatus", "read")
                          .eq("uuid", uuid)
                          .eq("businessEnum", MessageBusinessEnum.MSG_SYS_PLACARD)
                          .eq("deleted", false)
                          .order("read", "asc")
                          .order("createTime", "desc")
                          .page(jsonObject)
                          .exe();
    }

    public Object bulletinDetail(String id) {
        MessageAccount account = Pool.get(MessageAccount.class, id);
        if (Objects.isNull(account))
            return Result.error(0, "不存在该消息，请检查参数后重试！");

        checkMsgRead(account);

        if (Objects.isEmpty(account.getCompanyNum()))
            return Result.success(Pool.get(Message.class, account.getMsgId()));
        else
            return Result.success(Pool.get(MessageCorp.class, account.getMsgId()));
    }

    public Object del(String id){
        MessageAccount account = Pool.get(MessageAccount.class, id);
        if (Objects.isNull(account))
            return Result.error(0, "不存在该消息，请检查参数后重试！");

        account.setDeleted(true);
        jdbcSession.updateById(account);
        return Result.success();
    }

    public Object allList(JSONObject jsonObject, String uuid, String companyNo, Timestamp createTime, boolean userCreate) {
        checkUserLatest(uuid, companyNo, createTime, userCreate);

        return jdbcSession.findPage(MessageAccount.class)
                          .eq(jsonObject, "successStatus", "businessEnum")
                          .eq("uuid", uuid)
                          .eq("deleted", false)
                          .order("read", "asc")
                          .order("createTime", "desc")
                          .page(jsonObject)
                          .exe();
    }

    public Object allNoreadCount(String companyNo, String uuid){
        int count = jdbcSession.findArray(MessageAccount.class)
                               .eq("read", false)
                               .eq("uuid", uuid)
                               .eq("deleted", false)
                               .exe()
                               .size();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("allNoreadCount", count);
        return jsonObject;
    }

    private void checkUserLatest(String uuid, String companyNo, Timestamp userCreateTime, boolean userCreate){
        synchronized (uuid.intern()){
            Timestamp now = new Timestamp(TimeUtil.timestamp().getTime());
            Timestamp lastTime;// 上一次更新时间
            UserExpand user = Pool.get(UserExpand.class, uuid);
            if (Objects.isNull(user)) {
                lastTime = userCreateTime;

                user = Pool.newInstance(UserExpand.class, uuid);
                user.setLastTime(now);
                user.setUserCreate(userCreate);
                jdbcSession.insert(user);
            } else {
                lastTime = user.getLastTime();

                user.setLastTime(now);
                jdbcSession.updateById(user);
            }

            if (!userCreate){
                MessageAccountConfig accountConfig = configService.getAccountConfig(uuid);
                if (!accountConfig.isSysNotice())
                    return;
            }

            // 拉平台的消息
            FindArray<Message> findArray = jdbcSession.findArray(Message.class)
                                                      .maxEq("createTime", lastTime);
            if (userCreate) {
                findArray.eq("receiver", MessageReceiverType.ALL_CUSTOMER);
            } else {
                findArray.eq("receiver", MessageReceiverType.ALL_EMPLOYEE);
            }

            List<Message> messageList = findArray.eq("releaseStatus", true)
                                                 .eq("deleted", false)
                                                 .exe();

            messageList.forEach(item -> {
                MessageAccount account = Pool.newInstance(MessageAccount.class);
                account.setUuid(uuid);
                account.setMsgId(item.getId());
                account.setBusinessEnum(MessageBusinessEnum.MSG_SYS_PLACARD);
                account.setTemplateEnum(TemplateType.SYS_MESSAGE);
                account.setTitle(item.getTitle());
                account.setContent(item.getClassifyName());
                account.setCompanyNum(null);
                account.setSuccessStatus(true);
                account.setRead(false);
                account.setUserCreate(userCreate);
                account.setDeleted(false);
                jdbcSession.insert(account);
            });

            // 拉企业的消息
            FindArray<MessageCorp> findArrayCorp = jdbcSession.findArray(MessageCorp.class)
                                                      .maxEq("createTime", lastTime);
            if (userCreate) {
                findArrayCorp.eq("receiver", MessageReceiverType.ALL_CUSTOMER);
            } else {
                findArrayCorp.eq("receiver", MessageReceiverType.ALL_EMPLOYEE);
            }

            List<MessageCorp> messageCorpList = findArrayCorp.eq("releaseStatus", true)
                                                 .eq("deleted", false)
                                                 .exe();

            messageCorpList.forEach(item -> {
                MessageAccount account = Pool.newInstance(MessageAccount.class);
                account.setUuid(uuid);
                account.setMsgId(item.getId());
                account.setBusinessEnum(MessageBusinessEnum.MSG_SYS_PLACARD);
                account.setTemplateEnum(TemplateType.SYS_MESSAGE);
                account.setTitle(item.getTitle());
                account.setContent(item.getClassifyName());
                account.setCompanyNum(companyNo);
                account.setSuccessStatus(true);
                account.setRead(false);
                account.setUserCreate(userCreate);
                account.setDeleted(false);
                jdbcSession.insert(account);
            });
        }
    }

    /**
     * 统一消息入口
     * @return
     */
    @ReqMapping("/uniformSend")
    public Object uniformSend(String temp){
        logger.info("MessageService.uniformSend请求消息参数:{}", temp);
        UniformSendReqDto reqDto = JSONObject.parseObject(temp, UniformSendReqDto.class);

        // TemplateType templateType = Enums.getEnum(TemplateType.class, reqDto.getTemplateTypeId());
        // if (Objects.isNull(templateType))
        //     return Result.error(0, "不存在该模板类型");

        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(reqDto.getTemplateTypeId());
        if (Objects.isNull(globalConfig)) {
            return Result.error(0, "不存在该模板配置");
        }
        logger.info("MessageService.uniformSend#globalConfig参数:{}", globalConfig.toString());

        if (globalConfig.isInnerSend())
            innerSend(reqDto);

        if (globalConfig.isAppSend())
            appSend(reqDto);

        if (globalConfig.isSmsSend())
            smsSend(reqDto);

        if (globalConfig.isWxchatSend())
            wxchatSend(reqDto);

        return Result.success();
    }

    /**
     * 站内信消息
     * @return
     */
    @ReqMapping("/innerSend")
    public Object innerSendTemp(String temp){
        logger.info("MessageService.innerSendTemp请求消息参数:{}", temp);
        UniformSendReqDto reqDto = JSONObject.parseObject(temp, UniformSendReqDto.class);
        return innerSend(reqDto);
    }

    public Object innerSend(UniformSendReqDto reqDto){

        logger.info("开始发送站内信~~~~~~~");
        if (Objects.isEmpty(reqDto.getInnerData()) || Objects.isEmpty(reqDto.getUuid()) || Objects.isEmpty(reqDto.getTemplateTypeId()))
            return Result.error(0, "请填写必填参数");

        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(reqDto.getTemplateTypeId());
        if (Objects.isNull(globalConfig))
            return Result.error(0, "不存在该模板配置");
        if (!globalConfig.isInnerSend())
            return Result.error(0, "配置不发送该消息");

        MessageTemplateInner inner = innerService.getInner(reqDto.getTemplateTypeId());
        if (Objects.isNull(inner))
            return Result.error(0, "站内信配置为空");

        MessageBusinessEnum businessEnum = Enums.getEnum(MessageBusinessEnum.class, reqDto.getBusinessTypeId());
        TemplateType templateType = Enums.getEnum(TemplateType.class, reqDto.getTemplateTypeId());
        boolean successStatus = MessageBusinessStateEnum.MSG_SUCCESS == inner.getBusinessStateEnum();

        // check employee config
        if (!reqDto.isUserCreate()) {
            // check pre business account config
            if (!successStatus) {
                MessageAccountConfig accountConfig = configService.getAccountConfig(reqDto.getUuid());
                switch (businessEnum) {
                    case MSG_WORK_ORDER:
                        if (!accountConfig.isPreWorkOrder())
                            return Result.error(0, "用户配置不开启站内信功能");
                    case MSG_RESIDENT:
                        if (!accountConfig.isPreApprove())
                            return Result.error(0, "用户配置不开启站内信功能");
                    case MSG_BILL_PAY:
                    case MSG_SYS_PLACARD:
                        // not check scope
                        break;
                    default:
                        return Result.error(0, "暂不支持该类型");
                }
            }
        }

        MessageAccount account = Pool.newInstance(MessageAccount.class);
        account.setUuid(reqDto.getUuid());
        account.setMsgId(reqDto.getMsgId());
        account.setBusinessEnum(businessEnum);
        account.setTemplateEnum(templateType);
        account.setTitle(inner.getTitle());
        account.setContent(reqDto.getInnerData());
        account.setCompanyNum(reqDto.getCompanyNo());
        account.setSuccessStatus(successStatus);
        account.setRead(false);
        account.setUserCreate(reqDto.isUserCreate());
        account.setDeleted(false);
        account.setPageParam(reqDto.getPageParam());
        jdbcSession.insert(account);

        return Result.success();
    }

    /**
     * 应用消息
     * @return
     */
    @ReqMapping("/appSend")
    public Object appSendTemp(String temp){
        logger.info("MessageService.appSendTemp请求消息参数:{}", temp);
        UniformSendReqDto reqDto = JSONObject.parseObject(temp, UniformSendReqDto.class);
        return appSend(reqDto);
    }
    public Object appSend(UniformSendReqDto reqDto) {
        logger.info("开始发送应用消息~~~~~~~");
        if (Objects.isEmpty(reqDto.getAppData())
            || Objects.isEmpty(reqDto.getCompanyNo())
            || Objects.isEmpty(reqDto.getUuid()))
            return Result.error(0, "请填写必填参数");

        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(reqDto.getTemplateTypeId());
        if (Objects.isNull(globalConfig))
            return Result.error(0, "不存在该模板配置");
        if (!globalConfig.isAppSend())
            return Result.error(0, "配置不发送该消息");

        try {

            if (Objects.nonEmpty(reqDto.getAppToUrl())) {
                JSONObject agentJson = doveClient.post("/kht-bin/wwout/agent/get", http -> {
                    http.addParam("companyNo", reqDto.getCompanyNo());
                });
                if (agentJson.getIntValue("code") == 200) {
                    String url = reqDto.getAppToUrl() + "&state=" + agentJson.getJSONObject("data")
                                                                             .getString("suiteId");
                    reqDto.setAppToUrl(url);
                }
            }

            logger.info("uniformSend.sendAppCard开始请求，参数:{}", reqDto.toString());
            JSONObject jsonObject = doveClient.post("/message/webwork/sendAppCard", http->{
                http.addParam("companyNo", reqDto.getCompanyNo());
                http.addParam("uuid", reqDto.getUuid());
                http.addParam("content", reqDto.getAppData());
                http.addParam("title", reqDto.getTitle());
                http.addParam("appToUrl", reqDto.getAppToUrl());
            });
            logger.info("发送应用消息，参数：{}-{}-{}：{}",reqDto.getCompanyNo(), reqDto.getUuid(), reqDto.getAppData(), jsonObject.toJSONString());

            if (jsonObject.getIntValue("code") == 200) {
                return Result.success(jsonObject.getJSONObject("data"));
            } else {
                return Result.error(0, jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(0, e.getMessage());
        }
    }

    /**
     * 短信
     * @return
     */
    @ReqMapping("/smsSend")
    public Object smsSendTemp(String temp){
        logger.info("MessageService.smsSendTemp请求消息参数:{}", temp);
        UniformSendReqDto reqDto = JSONObject.parseObject(temp, UniformSendReqDto.class);
        return smsSend(reqDto);
    }
    public Object smsSend(UniformSendReqDto reqDto){
        logger.info("开始发送短信~~~~~~~");
        if (Objects.isEmpty(reqDto.getTemplateTypeId()) || Objects.isEmpty(reqDto.getPhoneList()))
            return Result.error(0, "请填写必填参数");

        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(reqDto.getTemplateTypeId());
        if (Objects.isNull(globalConfig))
            return Result.error(0, "不存在该模板配置");
        if (!globalConfig.isSmsSend())
            return Result.error(0, "配置不发送该消息");
        if (Objects.isEmpty(globalConfig.getSmsTemplate()))
            return Result.error(0, "没有申请该模板");

        MessageTemplateSms templateSms = Pool.get(MessageTemplateSms.class, globalConfig.getSmsTemplate());
        if (Objects.isNull(templateSms))
            return Result.error(0, "没有申请该模板");
        if (templateSms.getStatusCode() != 0)
            return Result.error(0, "审核中或者审核失败");
        if (templateSms.getTencentTemplateId() == 0)
            return Result.error(0, "模板异常~~请联系管理员！");

        try {
            String sign = "客户通科技";
            if (reqDto.isUserCreate()) {
                sign = "美好小区";
            }
            logger.info("uniformSend.smsSend开始请求，参数:{}", reqDto.toString());
            JSONObject resultJson = tencentSmsService.sendSms(reqDto.getPhoneList(), reqDto.getSmsDataParams(), templateSms.getTencentTemplateId(), sign, templateSms.getTencentContent());
            logger.info("uniformSend.smsSend返回结果：{}", resultJson.toJSONString());
            return Result.success(resultJson);
        } catch (Exception e){

            return Result.error(0, e.getMessage());
        }
    }
    @ReqMapping("/test")
    public Object test (String id){
        // JSONObject jsonObject = JSONObject.parseObject(id);

        UniformSendReqDto dto = JSONObject.parseObject(id, UniformSendReqDto.class);

        wxchatSend(dto);

        return Result.success();
    }

    /**
     * 公众号
     * @return
     */
    @ReqMapping("/wxchatSend")
    public Object wxchatSendTemp(String temp){
        logger.info("MessageService.wxchatSendTemp请求消息参数:{}", temp);
        UniformSendReqDto reqDto = JSONObject.parseObject(temp, UniformSendReqDto.class);
        return wxchatSend(reqDto);
    }
    public Object wxchatSend(UniformSendReqDto reqDto){
        logger.info("开始发送公众号消息~~~~~~~");
        if (Objects.isEmpty(reqDto.getTemplateTypeId())
            || Objects.isEmpty(reqDto.getWxChatData())
            || Objects.isEmpty(reqDto.getUuid())
            || Objects.isEmpty(reqDto.getCompanyNo()))
            return Result.error(0, "请填写必填参数");

        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(reqDto.getTemplateTypeId());
        if (Objects.isNull(globalConfig))
            return Result.error(0, "不存在该模板配置");
        if (!globalConfig.isWxchatSend())
            return Result.error(0, "配置不发送该消息");

        if (Objects.isEmpty(reqDto.getOpenId()) && !reqDto.isUserCreate()){
            logger.info("不允许给员工发送消息，参数为{}", reqDto.toString());
            return Result.error(0, "不允许给员工发送消息");
        }

        try {
            JSONObject jsonObject = doveClient.post("/message/mini/uniformSend", (http) -> {
                if (Objects.nonEmpty(reqDto.getPageParam()))
                    http.addParam("param", reqDto.getPageParam());

                if (Objects.nonEmpty(reqDto.getOpenId()))
                    http.addParam("openid", reqDto.getOpenId());

                http.addParam("templateType", reqDto.getTemplateTypeId());
                http.addParam("companyNo", reqDto.getCompanyNo());
                http.addParam("uuid", reqDto.getUuid());
                JSONObject body = new JSONObject();
                body.put("data", reqDto.getWxChatData());
                http.setBody(body.toString());
            });
            if (jsonObject.getIntValue("code") == 200) {
                return Result.success();
            }
            return Result.error(0, jsonObject.getString("message"));
        } catch (Exception e) {
            return Result.error(0, e.getMessage());
        }
    }

    public Object workbenchCount(String uuid) {

        JSONObject resultJson = new JSONObject();
        List<MessageAccount> remindList = jdbcSession.findArray(MessageAccount.class)
                                                     .eq("uuid", uuid)
                                                     .eq("read", false)
                                                     .noEq("businessEnum", MessageBusinessEnum.MSG_SYS_PLACARD)
                                                     .eq("deleted", false)
                                                     .order("createTime", "desc")
                                                     .exe();
        if (Objects.nonEmpty(remindList)){
            resultJson.put("remind", remindList.get(0));
            resultJson.put("remindNoReadCount", remindList.size());
        } else {
            resultJson.put("remind", null);
            resultJson.put("remindNoReadCount", 0);
        }

        List<MessageAccount> bulletinList = jdbcSession.findArray(MessageAccount.class)
                                                       .eq("uuid", uuid)
                                                       .eq("read", false)
                                                       .eq("businessEnum", MessageBusinessEnum.MSG_SYS_PLACARD)
                                                       .eq("deleted", false)
                                                       .order("createTime", "desc")
                                                       .exe();
        if (Objects.nonEmpty(bulletinList)){
            resultJson.put("bulletin", bulletinList.get(0));
            resultJson.put("bulletinNoReadCount", bulletinList.size());
        } else {
            resultJson.put("bulletin", null);
            resultJson.put("bulletinNoReadCount", 0);
        }

        return Result.success(resultJson);
    }

    @Deprecated
    public Object listMessageUser(JSONObject jsonObject, String uuid, Timestamp createTime, boolean userCreate) {
        checkLatest(uuid, createTime, userCreate);

        return Result.success(jdbcSession.findPage(MessageUser.class)
                                         .eq("uuid", uuid)
                                         .eq("releaseStatus", true)
                                         .eq("deleted", false)
                                         .order("createTime", "desc")
                                         .page(jsonObject)
                                         .exe());
    }

    @Deprecated
    private void checkLatest(String uuid, Timestamp userCreateTime, boolean userCreate){
        synchronized (uuid.intern()){
            Timestamp now = new Timestamp(TimeUtil.timestamp().getTime());
            Timestamp lastTime;// 上一次更新时间
            UserExpand user = Pool.get(UserExpand.class, uuid);
            if (Objects.isNull(user)) {
                lastTime = userCreateTime;

                user = Pool.newInstance(UserExpand.class, uuid);
                user.setLastTime(now);
                user.setUserCreate(userCreate);
                jdbcSession.insert(user);
            } else {
                lastTime = user.getLastTime();

                user.setLastTime(now);
                jdbcSession.updateById(user);
            }

            FindArray<Message> findArray = jdbcSession.findArray(Message.class)
                                                      .maxEq("createTime", lastTime);
            if (userCreate) {
                findArray.eq("receiver", MessageReceiverType.ALL_CUSTOMER);
            } else {
                findArray.eq("receiver", MessageReceiverType.ALL_EMPLOYEE);
            }

            List<Message> messageList = findArray.eq("releaseStatus", true)
                .eq("deleted", false)
                .exe();

            messageList.forEach(item -> {
                MessageUser messageUser = Pool.newInstance(MessageUser.class);
                messageUser.setUuid(uuid);
                messageUser.setMsgId(item.getId());
                messageUser.setType(MessageType.MESSAGE);
                messageUser.setTitle(item.getTitle());
                messageUser.setClassifyId(item.getClassifyId());
                messageUser.setClassifyName(item.getClassifyName());
                messageUser.setReleaseStatus(item.isReleaseStatus());
                messageUser.setUserCreate(userCreate);
                messageUser.setCreateTime(item.getCreateTime());
                jdbcSession.insert(messageUser);
            });
        }
    }

    @Deprecated
    public Object detail(MessageUser messageUser) {
        if (Objects.isNull(messageUser)) {
            return Result.error(0, "该消息不存在");
        }

        if (messageUser.getType() == MessageType.MESSAGE) {
            Message message =  Pool.get(Message.class, messageUser.getMsgId());

            if (!messageUser.isRead()) {
                synchronized (messageUser.getMsgId().intern()) {
                    messageUser.setRead(true);
                    jdbcSession.updateById(messageUser);

                    // 阅读数+1
                    int readNum = message.getReadNum() + 1;
                    message.setReadNum(readNum);
                    jdbcSession.updateById(message);
                }
            }

            return Result.success(message);
        }

        return Result.error(0, "暂不支持该消息类型");
    }

    @Deprecated
    public Object appDetail(MessageNotifyEmployee employee) {
        if (Objects.isNull(employee)) {
            return Result.error(0, "该消息不存在");
        }

        if (!employee.isRead()) {
            synchronized (employee.getId().intern()) {
                employee.setRead(true);
                jdbcSession.updateById(employee);
            }
        }

        return Result.success();
    }

    @Deprecated
    public Object employeeMessages(JSONObject jsonObject, String uuid) {

        Page<MessageNotifyEmployee> notifyEmployeePage = jdbcSession.findPage(MessageNotifyEmployee.class)
                                                                    .eq("uuid", uuid)
                                                                    .order("read", "asc")
                                                                    .order("createTime", "desc")
                                                                    .page(jsonObject)
                                                                    .exe();

        return Result.success(notifyEmployeePage);
    }

    @Deprecated
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/notify/employee")
    public void notifyEmployee(MessageNotifyEmployee notifyEmployee) {
        jdbcSession.insert(notifyEmployee);
    }

    @Deprecated
    public Object workbenchPage(String uuid) {

        JSONObject resultJson = new JSONObject();
        List<MessageNotifyEmployee> notifyEmployeeList = jdbcSession.findArray(MessageNotifyEmployee.class)
                                                                    .eq("uuid", uuid)
                                                                    .order("createTime", "desc")
                                                                    .exe();
        if (Objects.nonEmpty(notifyEmployeeList)){
            resultJson.put("remind", notifyEmployeeList.get(0));

            long remindCount = notifyEmployeeList.stream().filter(e -> !e.isRead()).count();
            resultJson.put("remindNoReadCount", remindCount);
        } else {
            resultJson.put("remind", null);
            resultJson.put("remindNoReadCount", 0);
        }

        List<MessageUser> messageUserList = jdbcSession.findArray(MessageUser.class)
                                                       .eq("uuid", uuid)
                                                       .eq("releaseStatus", true)
                                                       .eq("deleted", false)
                                                       .order("createTime", "desc")
                                                       .exe();
        if (Objects.nonEmpty(messageUserList)){
            resultJson.put("bulletin", messageUserList.get(0));
            long bulletinCount = messageUserList.stream().filter(e -> !e.isRead()).count();
            resultJson.put("bulletinNoReadCount", bulletinCount);
        } else {
            resultJson.put("bulletin", null);
            resultJson.put("bulletinNoReadCount", 0);
        }

        return Result.success(resultJson);
    }

}
